package com.super8.super8newtv;

import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.VideoView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.xhb.xbanner.XBanner;
import com.super8.super8newtv.bean.FullScreenBean;
import com.super8.super8newtv.bean.ImagesBean;
import com.super8.super8newtv.utils.FileUtil;
import com.super8.super8newtv.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 电子房价牌-全屏广告页面
 */
public class FullScreenActivity extends Activity {
    @BindView(R.id.xbanner)
    XBanner mXBanner;//图片

    @BindView(R.id.video_view)
    VideoView mVideoView;//全屏_视频

    List<ImagesBean> lsImg;
    List<String> lsImgUrl, lsVideoName;

    FullScreenBean fullScreenBean;

    int currentPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_screen);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        lsImg = new Gson().fromJson(intent.getStringExtra("lsImg"), new TypeToken<List<ImagesBean>>() {
        }.getType());
        lsImgUrl = new Gson().fromJson(intent.getStringExtra("lsImgUrl"), new TypeToken<List<String>>() {
        }.getType());
        lsVideoName = new Gson().fromJson(intent.getStringExtra("lsVideoName"), new TypeToken<List<String>>() {
        }.getType());

        fullScreenBean = new Gson().fromJson(intent.getStringExtra("fullScreenBean"), FullScreenBean.class);
        if (fullScreenBean != null) {
            if (fullScreenBean.getLsImage() != null)
                lsImg = fullScreenBean.getLsImage();
            if (fullScreenBean.getLsVideoName() != null && fullScreenBean.getLsVideoName().size() > 0) {
                lsVideoName = new ArrayList<>();
                String printTxtPath = getApplicationContext().getFilesDir().getAbsolutePath();
                for (String name : fullScreenBean.getLsVideoName()) {
                    if (FileUtil.isFileExist(printTxtPath + "/" + name))//检测文件是否存在
                        lsVideoName.add(name);
                }
            }
        }

        if (lsImg != null && lsImg.size() > 0)
            lsImgUrl = new ArrayList<>();
        for (ImagesBean bean : lsImg)
            lsImgUrl.add(bean.getXBannerUrl().toString());
        loadBanner();
    }

    /**
     * 加载 播放轮播图 imgUrlList
     */
    private void loadBanner() {
        if ((lsImg == null || lsImg.size() == 0) && (lsVideoName == null || lsVideoName.size() == 0)) {
            finish();//关闭
            return;
        }
//        LogUtils.e("loadBanner", new Gson().toJson(lsVideoName));
        if (lsImg != null && lsImg.size() > 0) {
            mXBanner.setVisibility(View.VISIBLE);
            mVideoView.setVisibility(View.GONE);
            //加载广告图片
            mXBanner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, View view, int position) {
                    SimpleDraweeView draweeView = (SimpleDraweeView) view;
                    draweeView.setImageURI(Uri.parse(lsImgUrl.get(position)));
                }
            });
            final int[] index = {0};
            //轮播图 滚动 监听事件
            mXBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    if (state == 2) {  //当滑动完毕的时候
                        index[0] = index[0] + 1;
                        if (index[0] > lsImgUrl.size()) {
                            playVideo(lsImg, lsImgUrl);//直接跳转视频播放
                        }
                    }
                }
            });

            //添加轮播图片数据
            mXBanner.setBannerData(R.layout.layout_fresco_homebanner, lsImg);
        } else {
            playVideo(lsImg, lsImgUrl);//直接跳转视频播放
        }
    }


    /**
     * 加载 播放视频
     */
    private void playVideo(final List<ImagesBean> lsImg, final List<String> lsUrl) {
        if (lsVideoName != null && lsVideoName.size() > 0) {
            //设置播放视频
            String absolutePath = getApplicationContext().getFilesDir().getAbsolutePath() + "/";
            //播放视频  半屏
            mXBanner.setVisibility(View.GONE);
            mVideoView.setVisibility(View.VISIBLE);
            currentPosition = 0;
            //监听视频资源装载完成
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mVideoView.start();//开始播放视频
                }
            });
            //监听视频播放完成
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mVideoView.stopPlayback();
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsVideoName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsVideoName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                mVideoView.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            finish();//关闭
                        }
                    } else {
                        finish();//关闭
                    }
                }
            });
            //监听视频播放出错
            mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
//                    LogUtils.e("OnErrorListener","监听视频播放出错");
                    stopPlaybackVideo();
                   //当前视频播放异常  播放下个
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsVideoName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsVideoName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                mVideoView.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            finish();//关闭
                        }
                    } else {
                        finish();//关闭
                    }
                    return true;
                }
            });
            try {
                mVideoView.stopPlayback();
                //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径4" + uri);
                String uri = absolutePath + lsVideoName.get(currentPosition);
                if (!TextUtils.isEmpty(uri)) {
                    mVideoView.setVideoURI(Uri.parse(uri));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            finish();//关闭
        }
    }

    private void stopPlaybackVideo() {
        try {
            mVideoView.stopPlayback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}